package com.eebbk.tfd.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * @author tangfudong
 * @date 2020/8/6
 */
@Configuration
//注入mapper
@MapperScan(basePackages = "com.eebbk.tfd.question.contentprod.dao.**", sqlSessionTemplateRef = "contentProdSqlSessionTemplate")
public class ContentProdDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.content-prod")//设置配置
    public DataSource contentProdDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory contentProdSqlSessionFactory(@Qualifier("contentProdDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        //设置对应的xml文件位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/eebbk/tfd/question/contentprod/dao/*.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager contentProdTransactionManager(@Qualifier("contentProdDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate contentProdSqlSessionTemplate(@Qualifier("contentProdSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
